package com.stylefeng.guns.rest.modular.artitle.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.stylefeng.guns.rest.common.CommonResponse;
import com.stylefeng.guns.rest.common.base.Constans;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.exception.BussinessException;
import com.stylefeng.guns.rest.common.persistence.model.Article;
import com.stylefeng.guns.rest.common.utils.TextUtil;
import com.stylefeng.guns.rest.common.utils.aliyunoss.OSSUploadUtil;
import com.stylefeng.guns.rest.modular.artitle.controller.dto.*;
import com.stylefeng.guns.rest.modular.artitle.service.ArticleService;
import com.stylefeng.guns.rest.modular.attent.controller.dto.AttentHotRequest;
import com.stylefeng.guns.rest.modular.attent.service.CareService;
import com.stylefeng.guns.rest.modular.catalogy.controller.dto.ArticleRequest;
import com.stylefeng.guns.rest.modular.content.service.ContentService;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ASUS-PC on 2018/6/26.
 */
@RestController
@RequestMapping("/article")
public class ArtitleController {
    private final Log logger = org.apache.commons.logging.LogFactory.getLog(this.getClass());
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CareService careService;
    @Autowired
    private ContentService contentService;

    /**
     * 获取用户最受欢迎的前15个创作
     * @param request
     * @return
     */
    /*@RequestMapping(value = "/deleteTest", method = RequestMethod.POST)
    public ResponseEntity<?> dsfsfsdfsdfsdf(@RequestBody AttentHotRequest request){
        contentService.deleteAllContentByArtitleId(request.getUserId());
        return ResponseEntity.ok(CommonResponse.ok(null));

    }*/

    /**
     * 用户发布视频
     * @param userId
     * @param
     * @return
     */
    @RequestMapping(value = "/publish" , method = RequestMethod.POST)
    public ResponseEntity<?> updateAvatar(@RequestParam(value = "userId" , required = true) int userId,
                                          @RequestParam(value = "title" , required = true) String title,
                                          @RequestParam(value = "descript" , required = false) String descript,
                                          @RequestParam(value = "catalogyId" , required = true) int catalogyId,
                                          @RequestParam(value = "duration" , required = true) int duration,
                                          @RequestParam(value = "address" , required = true) String address,
                                          @RequestParam(value = "vedioId" , required = true) String vedioId,
                                          @RequestParam(value = "file" , required = false) MultipartFile file){
        if(userId==0 || catalogyId == 0 || TextUtil.isEmpty(title)){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        String urlPath = "" ;
        if(file!=null || !file.isEmpty()){
            logger.info("publish file is :"+file.getOriginalFilename());
            urlPath = OSSUploadUtil.getInsance().uploadMultiAudioFile(file,"image");
            if(TextUtil.isEmpty(urlPath)){
                throw new BussinessException(BizExceptionEnum.FILE_UPLOAD_FAIL);
            }
        }
        //插入文件表
        /*FileEntity fileEntity = new FileEntity();
        fileEntity.setFilePath(urlPath);
        fileEntity.setName(file.getOriginalFilename());
        fileEntity.setSize((int)file.getSize());
        fileEntity.setDuration(duration);
        fileEntity.setCreateTime(new Date());
        boolean state = fileService.insertFile(fileEntity);
        if(!state){
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }*/


        GetPlayInfoResponse.PlayInfo p = getPlayInfoFromVideoId(vedioId.substring(1,title.length()-1));

        //插入文章表
        Article article = new Article();
        article.setCatagoryId(catalogyId);
        article.setTitle(title.substring(1,title.length()-1));
        article.setDecript(descript);
        article.setBgImage(urlPath);
        article.setCreateTime(new Date());
        article.setType(1);//本地上传视频
        article.setUserId(userId);
        article.setAddress(address.substring(1,address.length()-1));
        article.setVideoLength(duration);
        if(p!=null){
            article.setUrl(p.getPlayURL());
        }
        article.setVedioId(vedioId.substring(1,title.length()-1));

        if(articleService.insertArtitle(article)){
            article.setUrl(urlPath);
            return ResponseEntity.ok(CommonResponse.ok("操作成功" , article));
        }else {
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
    }


    /**
     * 获取我的创作
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUserArticleList", method = RequestMethod.POST)
    public ResponseEntity<?> getUserArticleList(@RequestBody AttentHotRequest request){
        if(request.getUserId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        if(request.getPage()==0){
            request.setPage(1);
        }
        if(request.getSize()==0){
            request.setSize(100);
        }
        List<ArticleDetailResponse> articles = articleService.userArticleList(request);

        return ResponseEntity.ok(CommonResponse.ok("操作成功" , articles));

    }

    /**
     * 获取用户最受欢迎的前15个创作
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUserArticleByCare", method = RequestMethod.POST)
    public ResponseEntity<?> getUserArticleByCare(@RequestBody AttentHotRequest request){
        if(request.getUserId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        List<Article> articles = articleService.getUserArticleByCare(request);

        return ResponseEntity.ok(CommonResponse.ok("操作成功" , articles));

    }

    /**
     * 删除创作
     * @param request
     * @return
     */
    @RequestMapping(value = "/deletArtitle", method = RequestMethod.POST)
    public ResponseEntity<?> deletArtitle(@RequestBody ArticleRequest request){
        if(request.getArticleId()==0){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        boolean state = articleService.deletArtitle(request.getArticleId());
        if(state){
            //删除视频相关的点赞数据
            careService.deleteAllCares(request.getArticleId());
            //删除视频的所有回复信息
            contentService.deleteAllContentByArtitleId(request.getArticleId());

            //删除阿里云服务器上的文件
            Article article = articleService.getArticleById(request.getArticleId());
            if(article!=null){
                try {
                    DeleteVideoResponse response  = deleteVideo(article.getVedioId());
                    if(response!=null){
                        logger.info("---->>delete video from ali response: "+response.getRequestId());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                logger.info("---->>delete video from ali: "+article.getVedioId());
            }

            //删除服务器上的文件
            articleService.deleVedioFile(request.getArticleId());
            return ResponseEntity.ok(CommonResponse.ok("操作成功" , null));
        }else {
            throw new BussinessException(BizExceptionEnum.DELET_FAUIL);
        }
    }

    /**
     * 获取上传凭证
     * @param request
     * @return
     */
    @RequestMapping(value = "/getOssAccess", method = RequestMethod.POST)
    public ResponseEntity<?> getOssAccessData(@RequestBody AccessRequest request){
        if(TextUtil.isEmpty(request.getTitle()) || TextUtil.isEmpty(request.getFileName())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        CreateUploadVideoResponse response;
        try {
            response = createUploadVideo(request);
            if(response!=null){
                logger.info("oss get VideoId = "+response.getVideoId() + "\n");
                logger.info("UploadAddress = " + response.getUploadAddress() + "\n");
                logger.info("UploadAuth = " + response.getUploadAuth() + "\n");
                return ResponseEntity.ok(CommonResponse.ok(response));
            }else {
                logger.info("ErrorMessage = null");
                throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
            }
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
    }

    /**
     * 上传文章改版
     * @param request
     * @return
     */
    @RequestMapping(value = "/publishUrl", method = RequestMethod.POST)
    public ResponseEntity<?> uploadOssFileUrl(@RequestBody ArtitleBodyRequest request){
        if(request.getUserId()==0 || TextUtil.isEmpty(request.getTitle())
                || TextUtil.isEmpty(request.getVedioId())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }

//        GetPlayInfoResponse.PlayInfo p = getPlayInfoFromVideoId(request.getVedioId());
        PlayInfoBean playInfoBean = getPlayInfoBeanFromVideoId(request.getVedioId());
        //插入文章表
        Article article = new Article();
        if(request.getCatalogyId()>0){
            article.setCatagoryId(request.getCatalogyId());
            article.setCatagoryIds(request.getCatalogyId()+"");
        }
        if(!TextUtil.isEmpty(request.getCatagoryIds())){
            article.setCatagoryIds(request.getCatagoryIds());
        }
        article.setTitle(request.getTitle());
        article.setCreateTime(new Date());
        article.setType(1);//阿里云oss上传
        article.setUserId(request.getUserId());
        article.setAddress(request.getAddress());
        article.setVideoLength(request.getDuration());
        article.setBgImage(request.getFilePath());
        if(playInfoBean!=null){
            article.setUrl(playInfoBean.getPlayInfo().getPlayURL());
//            article.setBgImage(playInfoBean.getVideoBase().getCoverURL());
            logger.info("---->>>cover url: "+playInfoBean.getVideoBase().getCoverURL()+"---"+playInfoBean.getVideoBase().toString());
//            article.setVideoLength(Integer.parseInt(p.getDuration()));
        }
        article.setVedioId(request.getVedioId());
        if(articleService.insertArtitle(article)){
            return ResponseEntity.ok(CommonResponse.ok("操作成功" , article));
        }else {
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }

    }


    /**
     * 初始化阿里云oss上传服务
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws ClientException
     */
    public  DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
    /**
     * 获取视频上传地址和凭证
     * @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
     * @throws Exception
     */
    public  CreateUploadVideoResponse createUploadVideo(AccessRequest accessRequest) throws Exception {
        DefaultAcsClient client = initVodClient(Constans.ALIYUN_ACCESS_ACCOUNT,Constans.ALIYUN_ACCESS_SCRECT);
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setTitle(accessRequest.getTitle());
        request.setFileName(accessRequest.getFileName());
        JSONObject userData = new JSONObject();
        JSONObject messageCallback = new JSONObject();
        messageCallback.put("CallbackURL", "http://vlog.vkankr.com/vlog-rest/article/alinotify");
//        messageCallback.put("CallbackType", "http");
//        userData.put("MessageCallback", messageCallback.toJSONString());

        messageCallback.put("callbackBody",
                "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        messageCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
//        String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
        userData.put("callback",  messageCallback.toJSONString());

        JSONObject extend = new JSONObject();
        extend.put("MyId", "user-defined-id");
        userData.put("Extend", extend.toJSONString());
        request.setUserData(userData.toJSONString());
        return client.getAcsResponse(request);
    }

    /*获取播放地址函数*/
    public GetPlayInfoResponse getPlayInfo(String vedidId) throws Exception {
        DefaultAcsClient client = initVodClient(Constans.ALIYUN_ACCESS_ACCOUNT,Constans.ALIYUN_ACCESS_SCRECT);
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(vedidId);
        request.setStreamType("video");
        request.setFormats("mp4");
        /*request.setFormats("mp4");
        request.setStreamType("video");
        request.setDefinition("HD");*/
        return client.getAcsResponse(request);
    }

    //获取视频信息（暂时弃用）
    private GetPlayInfoResponse.PlayInfo getPlayInfoFromVideoId(String videoId){
        GetPlayInfoResponse response = null;
        GetPlayInfoResponse.PlayInfo p = null;
        try {
            response = getPlayInfo(videoId);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            //播放地址
            for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
                logger.info("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "-----"+playInfo.getDefinition()+"---"+playInfo.getDuration());
                if("OD".equals(playInfo.getDefinition())){
                    p = playInfo;
                    return p;
                }
            }
            //Base信息
            logger.info("VideoBase.Title = " + response.getVideoBase().getTitle() + "\n");
        } catch (Exception e) {
            logger.info("ErrorMessage = " + e.getLocalizedMessage());
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
        return null;
    }

    //获取视频信息（）
    private PlayInfoBean getPlayInfoBeanFromVideoId(String videoId){
        GetPlayInfoResponse response = null;
        GetPlayInfoResponse.PlayInfo p = null;
        GetPlayInfoResponse.VideoBase videoBase = null;
        PlayInfoBean playInfoBean = new PlayInfoBean();
        try {
            response = getPlayInfo(videoId);
            videoBase = response.getVideoBase();
            playInfoBean.setVideoBase(videoBase);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            //播放地址
            for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
                logger.info("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "-----"+playInfo.getDefinition()+"---"+playInfo.getDuration());
                if("OD".equals(playInfo.getDefinition())){
                    p = playInfo;
                    playInfoBean.setPlayInfo(p);
                    return playInfoBean;
                }
            }
        } catch (Exception e) {
            logger.info("ErrorMessage = " + e.getLocalizedMessage());
            throw new BussinessException(BizExceptionEnum.UNKNOWN_ERROR);
        }
        return null;
    }

    /**
     * 上传单张图片
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/uploadImage" , method = RequestMethod.POST)
    public ResponseEntity<?> updateAvatar(@RequestParam(value = "file") MultipartFile file) {
        if (file == null) {
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        String urlPath = "";
        if (file != null || !file.isEmpty()) {
            logger.info("publish file is :" + file.getOriginalFilename());
            urlPath = OSSUploadUtil.getInsance().uploadMultiAudioFile(file, "image");
            if (TextUtil.isEmpty(urlPath)) {
                throw new BussinessException(BizExceptionEnum.FILE_UPLOAD_FAIL);
            }
        }
        logger.debug("file uload success :" + urlPath);
        Map<String,String> datas = new HashMap<>();
        datas.put("filename",urlPath);
        return ResponseEntity.ok(CommonResponse.ok(datas));
    }

    /**
     * 配置阿里视频处理回调
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alinotify" , method = RequestMethod.POST)
    public void noticeAliUrl(HttpServletRequest request,HttpServletResponse response) throws Exception {
        logger.info("---->>alicallback post: in");

        /*String ossCallbackBody = GetPostBody(request.getInputStream(),
                Integer.parseInt(request.getHeader("content-length")));*/

        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try{
            reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null){
                sb.append(line);
            }
            logger.info("---->>alicallback post: "+sb.toString());
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     5. * 删除视频
     6. * @param client 发送请求客户端
     7. * @return DeleteVideoResponse 删除视频响应数据
     8. * @throws Exception
     9.*/
    public DeleteVideoResponse deleteVideo(String videoId) throws Exception {
        DefaultAcsClient client = initVodClient(Constans.ALIYUN_ACCESS_ACCOUNT,Constans.ALIYUN_ACCESS_SCRECT);
        DeleteVideoRequest request = new DeleteVideoRequest();
        //支持传入多个视频ID，多个用逗号分隔
        request.setVideoIds(videoId);
        return client.getAcsResponse(request);
    }

    /**
     * 获取时下流行的视频列表
     * 目前先根据播放量返回
     * @return
     */
    @RequestMapping(value = "/getFastionList", method = RequestMethod.POST)
    public ResponseEntity<?> getFastionList(){
        return ResponseEntity.ok(CommonResponse.ok("操作成功" ,articleService.getFactionList()));

    }

    /**
     * 上传单张视频背景图片（20200504新增，用于客户端上传视频背景图片）
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/uploadImageBg" , method = RequestMethod.POST)
    public ResponseEntity<?> updateVideoBg(@RequestParam(value = "file") MultipartFile file) {
        if (file == null) {
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        String urlPath = "";
        if (file != null || !file.isEmpty()) {
            logger.info("publish file is :" + file.getOriginalFilename());
            urlPath = OSSUploadUtil.getInsance().uploadSgleImageFileBg(file, "image");
            if (TextUtil.isEmpty(urlPath)) {
                throw new BussinessException(BizExceptionEnum.FILE_UPLOAD_FAIL);
            }
        }
        logger.debug("file uload success :" + urlPath);
        Map<String,String> datas = new HashMap<>();
        datas.put("filename",urlPath);
        return ResponseEntity.ok(CommonResponse.ok(datas));
    }

    /**
     * 获取播放地址凭证
     * @param request
     * @return
     */
    @RequestMapping(value = "/getPlayAuth", method = RequestMethod.POST)
    public ResponseEntity<?> getVedioPlayArthor(@RequestBody VideoRequest request) throws Exception{
        if(TextUtil.isEmpty(request.getVedioId())){
            throw new BussinessException(BizExceptionEnum.NEED_PARAMS);
        }
        DefaultAcsClient client = initVodClient(Constans.ALIYUN_ACCESS_ACCOUNT,Constans.ALIYUN_ACCESS_SCRECT);
        GetVideoPlayAuthResponse response = getVideoPlayAuth(client,request.getVedioId());
        System.out.print("PlayAuth = " + response.getPlayAuth() + "\n");
        return ResponseEntity.ok(CommonResponse.ok(response.getPlayAuth()));
    }

    /*获取播放凭证函数*/
    public static GetVideoPlayAuthResponse getVideoPlayAuth(DefaultAcsClient client,String vedioId) throws Exception {
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(vedioId);
        return client.getAcsResponse(request);
     }

    /**
     * 获取时下流行的视频列表
     * 目前先根据播放量返回
     * @return
     */
    @RequestMapping(value = "/testUrl", method = RequestMethod.POST)
    public ResponseEntity<?> test(){
        articleService.updateSSOUrl();
        return ResponseEntity.ok(CommonResponse.ok("操作成功" ,null));//articleService.getFactionList()

    }

}
